import os
import json



home_path = os.path.abspath(os.path.join(__file__, "../../../"))
def replace_context(filepath: str, replaceList):
    with open(filepath, 'r', encoding='utf-8') as file:
        file_content = file.read()
    for item in replaceList:
        old: str = item['old']
        new_str: str = item['new']
        # print("old:", old)
        # print("new:", new_str)
        index = file_content.find(old)
        if index < 0:
            print(f"file:[{filepath}]not find:[{old}]")
            return
        file_content = file_content.replace(old, new_str)
    with open(filepath, 'w', encoding='utf-8') as file:
        file.write(file_content)
    # print(filepath, "文件内容：")
    # print(file_content)

def replace_all(jsonfile:str):

    # 打开 JSON 文件
    with open(jsonfile, 'r', encoding='utf-8') as file:
        # 使用 load() 函数加载 JSON 数据
        data = json.load(file)

    for node in data:
        file: str = node['file']
        replace = node['replace']
        state = True
        # if not file.endswith("SocialClientServiceImpl.java"):
        #     state = False

        if state and len(replace) > 0:
            if file.startswith("\\"):
                file = file[len("\\"):]
            if file.startswith("/"):
                file = file[len("/"):]
            filepath = os.path.join(home_path, file)
            if os.path.exists(filepath) and os.path.isfile(filepath):
                replace_context(filepath, replace)

replace_all("java.json")
replace_all("maven.json")
replace_all("vm.json")
# 打印读取的 JSON 数据
